package com.zed.api.common.resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 基于模块内的Spring资源提取器
 *
 * @author Zed
 */
public class SpringResourcesExtractorWithModule {

    private static Logger LOGGER = LoggerFactory.getLogger(SpringResourcesExtractorWithModule.class);

    private ResourcesExtractor resourcesExtractor;

    private Class<?> targetClass;

    private URL url;

    public SpringResourcesExtractorWithModule(Class<?> targetClass) {
        this.targetClass = Objects.requireNonNull(targetClass, "\"targetClass\" cannot be null.");
        this.resourcesExtractor = new ResourcesExtractor();
        this.url = this.targetClass.getResource("");
    }


    /**
     * 提取并返回对应的URL
     *
     * @param callback {@link ResourceScanningCallback},回调
     * @return {@link List},扫描到的集合
     */
    public List<URL> extract(ResourceScanningCallback callback) {
        String protocol = this.url.getProtocol();

        if (Objects.equals(protocol, "jar")) {
            try {
                JarURLConnection jarURLConnection = (JarURLConnection) this.url.openConnection();
                URL jarFileURL = jarURLConnection.getJarFileURL();
                return this.resourcesExtractor.extract(jarFileURL, callback);
            } catch (IOException e) {
                LOGGER.warn("extract jar resources fail", e);
            }
        } else if (Objects.equals(protocol, "file")) {
            return this.resourcesExtractor.extract(this.url, callback);
        }

        return Collections.emptyList();
    }
}
